package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.service.AccountService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name="EditMyAccountServlet",urlPatterns = {"/editMyAccountServlet"})
public class EditMyAccountServlet extends HttpServlet {

    private AccountService accountService;
    private boolean isValid=true;//标志修改是否有效
    String msg;//如果修改的无效，则显示错误信息
    private static final String EDIT_ACCOUNT_FORM = "/WEB-INF/jsp/account/editAccountForm.jsp";


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session=req.getSession();
        Account account1;


        //获取输入的 数据
        Account account=(Account)session.getAttribute("loginAccount");
        String username=account.getUsername();
        String password = req.getParameter("password");
        String repeatedPassword=req.getParameter("repeatedPassword");
        String firstName = req.getParameter("firstName");
        String lastName = req.getParameter("lastName");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String address1 = req.getParameter("address1");
        String address2 = req.getParameter("address2");
        String city = req.getParameter("city");
        String state = req.getParameter("state");
        String zip = req.getParameter("zip");
        String country = req.getParameter("country");
        String languagePreference = req.getParameter("languagePreference");
        String favouriteCategoryId = req.getParameter("favouriteCategoryId");
        String listOption = req.getParameter("listOption");
        String bannerOption = req.getParameter("bannerOption");

        //信息存为account1，但是在验证有效性后才会更新数据库
        account1 = new Account();
        account1.setUsername(username);
        account1.setPassword(password);
        account1.setFirstName(firstName);
        account1.setLastName(lastName);
        account1.setEmail(email);
        account1.setPhone(phone);
        account1.setAddress1(address1);
        account1.setAddress2(address2);
        account1.setCity(city);
        account1.setState(state);
        account1.setZip(zip);
        account1.setCountry(country);
        account1.setLanguagePreference(languagePreference);
        account1.setFavouriteCategoryId(favouriteCategoryId);
        account1.setListOption(Boolean.parseBoolean(listOption));
        account1.setBannerOption(Boolean.parseBoolean(bannerOption));


            if (!isValid(account1, repeatedPassword)) {
                System.out.println("不符合规则");
                //不符合输入规则，提示错误信息
                session.setAttribute("messageAccount", this.msg);
                //回到页面
                req.getRequestDispatcher(EDIT_ACCOUNT_FORM).forward(req, resp);
            } else {
                System.out.println("符合规则");

                session.setAttribute("action","updatedNewAccountInf");

                //符合输规则，注册账号
                //将数据存成一个账户
                accountService = new AccountService();
                accountService.updateAccount(account1);
                session.setAttribute("loginAccount",account1);
                //注册成功！回到主页面
                req.getRequestDispatcher(EDIT_ACCOUNT_FORM).forward(req, resp);
            }
        }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    public boolean isValid(Account account,String repeatedPassword){
            if (account.getFirstName().isEmpty() || account.getLastName().isEmpty() || account.getEmail().isEmpty() ||
                    account.getPhone().isEmpty() || account.getAddress1().isEmpty() || account.getCity().isEmpty() ||
                    account.getState().isEmpty() || account.getZip().isEmpty() || account.getCountry().isEmpty() ||
                    account.getLanguagePreference().isEmpty() || account.getFavouriteCategoryId().isEmpty()||
                    account.isListOption()||account.isBannerOption()) {
                isValid = false;
                this.msg = "所有字段都必须填写";
            } else if (!account.getPassword().equals(repeatedPassword)) {
                isValid = false;
                this.msg = "两次输入的密码不一致";
            } else if (!isValidEmail(account.getEmail())) {
                isValid = false;
                this.msg = "请输入有效的邮箱地址";
            } else if (!isValidPhone(account.getPhone())) {
                isValid = false;
                System.out.println(account.getPhone());
                this.msg = "请输入有效的电话号码";
            } else if (!isValidZip(account.getZip())) {
                isValid = false;
                this.msg = "请输入有效的邮政编码";
            }
        return isValid;


    }
    // 邮箱格式验证方法
    private boolean isValidEmail(String email) {
        String regex = "^[a-zA-Z0-9_+&*-]+(?:\\."+
                "[a-zA-Z0-9_+&*-]+)*@" +
                "(?:[a-zA-Z0-9-]+\\.)+[a-z" +
                "A-Z]{2,7}$";
        return email.matches(regex);
    }

    // 电话号码格式验证方法
    private boolean isValidPhone(String phone) {
        String regex = "^\\d{10}$"; // 假设电话号码必须是10位数字
        System.out.println(phone);
        return phone.matches(regex);
    }

    // 邮政编码格式验证方法
    private boolean isValidZip(String zip) {
        String regex = "^\\d{5}$"; // 假设邮政编码必须是5位数字
        return zip.matches(regex);
    }
}
